<?php

$save_path = '';
//var_dump($argv);

if ($s_key = array_search('saveto', $argv)) {
    $save_path = $argv[$s_key + 1];
    unset($argv[$s_key], $argv[$s_key + 1]);

} else {
    $save_path = 'txt';
}
rtrim($save_path, '\\');
$save_path = $save_path . DIRECTORY_SEPARATOR;

$in = "";
$str = "";
for ($i = 1; $i < count($argv); $i++) {
    $in = file_get_contents($argv[$i]);
    $enc = mb_detect_encoding($in, 'UTF-8,GBK,GB2312');
    $in = mb_convert_encoding($in, 'utf-8', "$enc,GBK");
    $str .= $in;
}

$enc = mb_detect_encoding($str, 'UTF-8,GBK,GB2312');
$str = mb_convert_encoding($str, 'utf-8', "$enc,GBK");
preg_match_all("/[\x{4e00}-\x{9fa5}]/u",$str,$matchs);
$str = implode($matchs[0]);

//$kong = array(" ", "　", "\t", "\n", "\r", PHP_EOL);
//$fuhao = '\'^\\$~。，？【】＼、‘’“”：*！《》；１２３４５６７８９０［］｛｝":.@_?&[,;};{©●}#]!|-·～＠＃￥％……＆×（）()——＋+1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
//';
//$fuhao .= '▪┊ ➀➁➂➃➄➅➆➇➈➉➊➋➌➍➎➏➐➑➒➓⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛㊀㊁㊂㊃㊄㊅㊆㊇㊈㊉ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ';
//$fuhao .= '﹢﹣×÷±/=≌∽≦≧≒﹤﹥≈≡≠=≤≥<>≮≯∷∶∫∮∝∞∧∨∑∏∪∩∈∵∴⊥∥∠⌒⊙√∟⊿㏒㏑%‰⅟½⅓⅕⅙⅛⅔⅖⅚⅜¾⅗⅝⅞⅘≂≃≄≅≆≇≈≉≊≋≌≍≎≏≐≑≒≓≔≕≖≗≘≙≚≛≜≝≞≟≠≡≢≣≤≥≦≧≨≩⊰⊱⋛⋚∫∬∭∮∯∰∱∲∳%℅‰‱øØπ';
//$str = str_replace($kong, '', $str);
//$str = str_replace(str_split_unicode($fuhao), '', $str);


$filename = 'out';

if (false !== strpos($argv[1], 'http')) {
    $filename = parse_url($argv[1])['host'];
} else {
    $filename = pathinfo($argv[1])["filename"];
}
$count = mb_strlen($str);

preg_match_all("/[\x{4e00}-\x{9fa5}0-9a-zA-Z\._-]/u",$filename,$matchs);

$filename = implode($matchs[0]);


if (!is_dir($save_path)) {
    if (!mkdir($save_path,0777,true)) {
        echo $save_path . PHP_EOL;
        die('创建保存目录失败，请检查原因');
    };

}

file_put_contents($save_path  . $filename . '-' . $count . '.txt', $str);

$msg = '本次整理出 ' . $count . ' 个字' . PHP_EOL . '保存在' . $save_path . $filename . '-' . $count . '.txt';
echo $msg;


/**
 * @param $str
 * @param int $length
 * @return array|array[]|false|string[]
 * 把字符串拆分为数组，支持中文等其它多字节语言
 */
function str_split_unicode($str, $length = 1)
{
    $tmp = preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY);
    if ($length > 1) {
        $chunks = array_chunk($tmp, $length);
        foreach ($chunks as $i => $chunk) {
            $chunks[$i] = join('', (array)$chunk);
        }
        $tmp = $chunks;
    }
    return $tmp;
}